package top.gytf.unifiedcall.producer.support.exception;

import lombok.AllArgsConstructor;
import top.gytf.unifiedcall.model.exception.BaseException;

import java.util.function.Function;

/**
 * 简单实现的支持单个的适配
 */
@AllArgsConstructor
public class SimpleExceptionAdapter<T extends Throwable> implements ExceptionAdapter {
    private final Class<T> supported;
    private final Function<T, BaseException> converter;
    private final int order;

    public SimpleExceptionAdapter(Class<T> supported, Function<T, BaseException> converter) {
        this(supported, converter, 0);
    }

    @Override
    public int order() {
        return order;
    }

    @Override
    public int calcSupportScore(Class<? extends Throwable> cls) {
        if (!supported.isAssignableFrom(cls)) {
            return -1;
        }

        int score = Integer.MAX_VALUE;
        Class<?> current = cls;
        while (current != Object.class && supported != current) {
            score--;
            current = current.getSuperclass();
        }
        return current == Object.class ? -1 : score;
    }

    @Override
    public BaseException convert(Throwable throwable) {
        return converter.apply(supported.cast(throwable));
    }
}
